package tracker

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"goDFS/etc"
	"goDFS/public"
	ncf "goDFS/synchronization"
	"net/http"
	"strings"
)

//获取全部的storage地址
func GetAllAddress(c *gin.Context) {

	ip := c.ClientIP()
	if !(ip[0:3] == "10." || ip[0:4] == "172." || ip[0:4] == "192." || ip == "127.0.0.1") {
		etc.SaveLog("[ GetAllAddress ]"+public.IpIsLan, 1)
		c.JSON(http.StatusNotAcceptable, public.NewJsonErrUseTem(public.IpIsLan, 0, ip))
		return
	}
	//TODO
	buf := loadBalancer.ToAddressString()
	c.String(http.StatusOK, buf)

}

//用户上传时，返回token和Addr
func GetToken(c *gin.Context) {
	//c.String(http.StatusOK,"getToken")
	//获取一个负载IP

	addr := loadBalancer.GetAddr()

	token, err := public.GetToken(addr, Conf.Tracker.Token)
	if err != nil {
		etc.SaveLog("[ GetToekn ]"+err.Error(), 3)
		c.JSON(http.StatusNotAcceptable, public.NewJsonErrUse(0, err.Error()))
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"token": token,
		"addr":  addr,
	})

}

//为用户的下载请求，进行重定向
func GetRed(c *gin.Context) {
	key := c.DefaultQuery("key", "")
	addr := loadBalancer.GetAddr()

	c.Redirect(http.StatusFound, fmt.Sprintf("http://%s/get?key=%s", addr, key))

}

//storage通过这个接口注册服务
func Register(c *gin.Context) {

	ip := c.DefaultQuery("ip", "")
	port := c.DefaultQuery("port", "")
	//只允许局域网ip使用

	if ip == "" || port == "" || len(ip) < 5 {
		etc.SaveLog("[ Register ]  must have ip and port ", 2)
		c.JSON(http.StatusNotAcceptable, public.NewJsonErrUse(0, "must have ip and port "))
		return
	}

	if !(ip[0:3] == "10." || ip[0:4] == "172." || ip[0:4] == "192.") {
		etc.SaveLog("[ Register ]"+public.IpIsLan, 2)
		c.JSON(http.StatusNotAcceptable, public.NewJsonErrUseTem(public.IpIsLan, 0, ip))
		return
	}

	addr := public.NewStorageAddr(ip, port)
	if addr == nil {
		etc.SaveLog("[ Register ]ip or port not right", 2)
		c.JSON(http.StatusNotAcceptable, public.NewJsonErrUse(0, "ip or port not right"))
		return
	}

	//注册到负载均衡器
	err := loadBalancer.RegisterAddr(addr)
	if err != nil {
		etc.SaveLog("[ Register ]"+err.Error(), 2)
		c.JSON(http.StatusNotAcceptable, public.NewJsonErrUse(0, err.Error()))
		return
	}

	c.String(http.StatusOK, "1")

}

//同步请求
func SyncFile(c *gin.Context) {

	local := c.DefaultQuery("local", "")
	key := c.DefaultQuery("key", "")
	if key == "" || local == "" {
		etc.SaveLog("[ SyncFile ]  must have loacl and key", 1)
		c.JSON(http.StatusNotAcceptable, public.NewJsonErrUse(1, "must have loacl and key"))
		return
	}

	l := strings.Split(local, ":")

	if len(l) != 2 {
		etc.SaveLog("[ SyncFile ]  key err", 1)
		c.JSON(http.StatusNotAcceptable, public.NewJsonErrUse(1, "key err"))
		return
	}

	bal := ncf.NewSyncFileAddress(l[0], l[1], key)
	if bal == nil {
		etc.SaveLog("[ SyncFile ]  key err", 1)
		c.JSON(http.StatusNotAcceptable, public.NewJsonErrUse(1, "key err"))
		return
	}

	//注册一个同步
	syncManager.AddSyncFile(bal)

	c.JSON(http.StatusOK, gin.H{
		"data": 1,
	})

}
